package com.liesheng.haylou.ui.main.equipment;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.view.LayoutInflater;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.liesheng.daemonlib.LogUtil;
import com.liesheng.haylou.R;
import com.liesheng.haylou.base.BaseActivity;
import com.liesheng.haylou.base.BaseFragment;
import com.liesheng.haylou.base.BaseFunActivity;
import com.liesheng.haylou.base.BaseVm;
import com.liesheng.haylou.bluetooth.BleDataInfo;
import com.liesheng.haylou.bluetooth.BleManager;
import com.liesheng.haylou.common.recycleView.CommonAdapter;
import com.liesheng.haylou.databinding.FragmentEquipmentBinding;
import com.liesheng.haylou.databinding.ItemDeviceListBinding;
import com.liesheng.haylou.db.DBManager;
import com.liesheng.haylou.db.entity.BoundedDevice;
import com.liesheng.haylou.event.AddBoundDeviceEvent;
import com.liesheng.haylou.event.DelDeviceEvent;
import com.liesheng.haylou.event.DeviceBatteryChangeEvent;
import com.liesheng.haylou.ui.device.DeviceDetailActivity;
import com.liesheng.haylou.ui.device.SearchDeviceActivity;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;


/**
 * Date:${DATA}
 * Author ${ZhangZhiQiang}
 * Description
 */
public class EquipmentFragment extends BaseFragment<FragmentEquipmentBinding, BaseVm> {

    List<BoundedDevice> devices;
    CommonAdapter adapter;

    @Override
    protected FragmentEquipmentBinding getDataBinding() {
        dataBinding = DataBindingUtil.inflate(LayoutInflater.from(getContext()), R.layout.fragment_equipment, null, false);
        return dataBinding;
    }

    @SuppressLint("WrongConstant")
    @Override
    protected void initData() {
        setTitle(R.string.my_device);
        devices = DBManager.getInstance().getDaoSession().getBoundedDeviceDao().queryBuilder().list();
        //倒序,最后添加的排在最前面
        Collections.reverse(devices);
        showEmptyLayout(devices.size() <= 0 ? true : false);

        dataBinding.recyclerV.setLayoutManager(new LinearLayoutManager(getContext()));
        initAdapter();
        dataBinding.recyclerV.setAdapter(adapter);

    }

    private void scanBle() {
        if (devices == null || devices.size() == 0)
            return;
        scanMap.clear();
        for (BoundedDevice device : devices) {
            device.setCharging(null);
            device.setBatteries(null);
            device.setHasScaned(false);
        }
        adapter.notifyDataSetChanged();

        if (((BaseActivity) getActivity()).isBluetoothOpen())
            BleManager.getInstance().scanBle(leScanCallback);
    }

    public void openBluetooth(boolean isOpen) {
        if (isOpen)
            scanBle();
    }

    @Override
    public void onResume() {
        super.onResume();
        LogUtil.d("onResume---" + this.getClass().getSimpleName());
        scanBle();
    }

    @Override
    protected boolean isRegistEventBus() {
        return true;
    }

    private void initAdapter() {
        adapter = new CommonAdapter<BoundedDevice, ItemDeviceListBinding>(getContext(), devices, R.layout.item_device_list) {

            @Override
            public void contentConvert(ItemDeviceListBinding binding, final BoundedDevice device, int position) {

                EquipmentItemVm vm = new EquipmentItemVm();
                binding.barBox.setEnabled(false);
                binding.barLeft.setEnabled(false);
                binding.barRight.setEnabled(false);

                switch (device.getType()) {
                    case 0:
                        binding.tvBlueType.setText(R.string.ble_type_headset);
                        break;
                }
                binding.tvBlueName.setText(getString(R.string.ble_name_address, device.getName(), device.getAddress()));
                final BluetoothGatt gatt = BleManager.getInstance().getBluetoothGatt(device.getAddress());
                vm.isConn.set(gatt != null);
                vm.hasScaned.set(device.isHasScaned() || vm.isConn.get());

                int[] bat = device.getBatteries();
                int[] charge = device.getCharging();
                if (bat != null) {
                    vm.setBatteries(bat[0], bat[1], bat[2]);
                    binding.tvBoxShow.setText(getStr(R.string.battery_box, bat[0]));
                    binding.tveLectricleft.setText(getStr(R.string.battery_left, bat[1]));
                    binding.tvLectricRight.setText(getStr(R.string.battery_left, bat[2]));
                    if (bat[0] <= 0)
                        binding.tvBoxShow.setText(getStr(R.string.battery_box_none));
                }
                if (charge != null) {
                    vm.setCharging(charge[0], charge[1], charge[2]);
                }

                binding.setVm(vm);

                binding.getRoot().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        DeviceDetailActivity.startBy((BaseFunActivity) getActivity(), device, gatt == null ? scanMap.get(device.getAddress()) : gatt.getDevice());
                    }
                });
            }
        };
    }

    private HashMap<String, BluetoothDevice> scanMap = new HashMap<>();
    BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice bluetoothDevice, int j, byte[] bytes) {

            BleDataInfo info = BleDataInfo.create(bytes, bluetoothDevice);
            if (scanMap.get(info.getrLaddress()) != null) return;

            if (info.canBeSearched()) {
                scanMap.put(info.getrLaddress(), bluetoothDevice);
                for (int i = 0; i < devices.size(); i++) {
                    if (scanMap.keySet().contains(devices.get(i).getAddress())) {
                        devices.get(i).setHasScaned(true);
                        devices.get(i).setBatteries(info.getBatteries());
                        devices.get(i).setCharging(info.getCharging());
                        adapter.notifyItemChanged(i);
                    }
                }

            }
        }
    };


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventPost(AddBoundDeviceEvent event) {
        if (devices.contains(event.device)) {
            return;
        }
        showEmptyLayout(false);
        devices.add(0, event.device);
        adapter.notifyDataSetChanged();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventPost(DeviceBatteryChangeEvent event) {

        if (devices != null && devices.size() > 0) {
            for (int i = 0; i < devices.size(); i++) {
                BoundedDevice dev = devices.get(i);
                if (dev.equals(event.bd)) {
                    dev.setCharging(event.bd.getCharging());
                    dev.setBatteries(event.bd.getBatteries());
                    adapter.notifyItemChanged(i);
                    break;
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventPost(DelDeviceEvent event) {
        if (devices != null && devices.size() > 0) {
            for (int i = 0; i < devices.size(); i++) {
                BoundedDevice dev = devices.get(i);
                if (dev.getAddress().equals(event.address)) {
                    devices.remove(i);
                    adapter.notifyDataSetChanged();
                    break;
                }
            }
        }
    }


    @Override
    public void onClickView(View view) {
        switch (view.getId()) {
            case R.id.addDevice:
                SearchDeviceActivity.startBy((BaseFunActivity) getActivity());
                break;
        }
    }

    @Override
    protected void onClickEmptyBtn() {
        super.onClickEmptyBtn();
        SearchDeviceActivity.startBy((BaseFunActivity) getActivity());
    }

    @Override
    public BaseVm getViewModel() {
        return null;
    }

}
